/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin		 	*/
/*	Project:	GlbLib-1.0.0			*/
/*	Author:		gong_libin			*/
/*	Date:		2016_06_01			*/
/*	File:		GlbUdpTest.cpp			*/
/********************************************************/

#include "GlbUdp.h"
#include "GlbTime.h"

using namespace GlbCls;
using namespace GlbNet;

void GlbUdpTestSend()
{
	CGlbUdp CUdp;
	CGlbTime CTime;
	UCHAR uszSend[GLB_PACKET] = { 0 };
	UCHAR uszRecv[GLB_PACKET] = { 0 };
	char szSnd[GLB_URL] = "192.168.2.221:12345";
	char szRcv[GLB_URL] = "192.168.2.221:54321";

	CTime.GlbTimeOn();

	if (GLB_SUCCESS == CUdp.GlbNetInitSend(szSnd)) {
		if (GLB_SUCCESS == CUdp.GlbNetBind(szRcv)) {
			memset(uszSend, 'A', GLB_PACKET / 8);
			if (CUdp.GlbNetSend(uszSend, strlen((char*)uszSend)) > 0) {
				GLB_PRINT("Send: %s\n", (char*)uszSend);
				if ((CUdp.GlbNetRecv(uszRecv, GLB_PACKET)) > 0) {
					GLB_PRINT("Recv: %s\n", (char*)uszRecv);
				}
				else {
					GLB_ERROR("Failed to GlbNetRecv\n");
				}
			}
			else {
				GLB_ERROR("Failed to GlbNetSend\n");
			}
		}
		else {
			GLB_ERROR("Failed to GlbNetBind\n");
		}
		CUdp.GlbNetClose();
	}

	CTime.GlbTimeOff();
	CTime.GlbTimeDisplay();

	return;
}

void GlbUdpTestRecv()
{
	CGlbUdp CUdp;
	CGlbTime CTime;
	UCHAR uszPacket[GLB_PACKET] = { 0 };
	char szAddr[GLB_URL] = "192.168.2.221:12345";

	if (GLB_SUCCESS == CUdp.GlbNetInitRecv(szAddr)) {
		while ((CUdp.GlbNetRecv(uszPacket, GLB_PACKET)) > 0) {
			CTime.GlbTimeOn();

			/* recv */
			GLB_PRINT("Recv: %s\n", (char*)uszPacket);
			GLB_PRINT("SrcPort: %d\t", ntohs(((struct sockaddr_in*)CUdp.GlbUdpGetAddr())->sin_port));
			GLB_PRINT("SrcAddr: %s\n", (char*)inet_ntoa(((struct sockaddr_in*)CUdp.GlbUdpGetAddr())->sin_addr));

			/* send */
			memset(uszPacket, 'B', GLB_PACKET / 16);
			if (CUdp.GlbNetSend(uszPacket, strlen((char*)uszPacket)) > 0) {
				GLB_PRINT("Send: %s\n", (char*)uszPacket);
			}
			else {
				GLB_ERROR("Failed to GlbNetSend\n");
			}

			CTime.GlbTimeOff();
			CTime.GlbTimeDisplay();
		}
		CUdp.GlbNetClose();
	}

	return;
}

int main(int argc, char* argv[])
{
	if (argc < 2) {
		GLB_PRINT("Usage: %s [send | recv]\n", argv[0]);
		return GLB_SUCCESS;
	}

	switch (strcmp(argv[1], "send")) {
		case 0:
			GlbUdpTestSend();
			break;
		default:
			GlbUdpTestRecv();
			break;
	}

	return GLB_SUCCESS;
}
